import 'dart:async';

import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_gesture_entity.dart';

import '../../events/user_change_event.dart';
import '../../service/manager/lf_event_helper.dart';
import '../../net/error_handle.dart';
import '../../net/lf_api_url.dart';
import '../../net/lf_dio_util.dart';
import '../../service/lf_auth_service.dart';
import '../../utils/lf_dialog_utils.dart';
import '../lf_base_controller.dart';

toVerifyPage({bool must = false}) {
  Get.toNamed(LFRoute.pathVerify, arguments: {'must': must});
}

class LfVerifyLogic extends GetxController {
  LfGestureEntity? gestureEntity;
  LoadingState loadingState = LoadingState.loading;
  LfAuthService authService = Get.find();
  late StreamSubscription<UserChangeEvent> _subscription;
  bool isMust = false;
  bool showedTips = false;

  @override
  void onInit() {
    isMust = Get.arguments['must'];
    super.onInit();
  }

  @override
  void onReady() {
    getGestureCode();
    super.onReady();
    _subscription =
        LfEventHelper().getEvent().on<UserChangeEvent>().listen((event) {
      if (event.userChangeAction == UserChangeAction.verify) {
        Get.back();
      }
    });
  }

  @override
  void onClose() {
    _subscription.cancel();
    super.onClose();
  }

  getGestureCode() {
    if (gestureEntity != null) {
      loadingState = LoadingState.success;
      update();
    } else if (loadingState != LoadingState.loading) {
      loadingState = LoadingState.loading;
      update();
    }
    LfDio.instance.get<LfGestureEntity>(url: apiVerifyGestureCode).then(
        (value) {
      gestureEntity = value;
      loadingState = LoadingState.success;
      update();
    }, onError: (error) {
      if (gestureEntity == null) {
        loadingState = LoadingState.failed;
      }
      update();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }
}
